<template>
  <div class="register-container">
    <div class="register-form">
      <h2>用户注册</h2>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" type="email" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="formData.password" 
            placeholder="请输入密码" 
            type="password" 
            show-password 
            @input="checkPasswordStrength"
          />
          <!-- 密码强度指示器 -->
          <div v-if="formData.password" class="password-strength">
            <div class="strength-bar">
              <div 
                class="strength-indicator"
                :class="{
                  'weak': passwordStrength === 1,
                  'medium': passwordStrength === 2,
                  'strong': passwordStrength === 3
                }"
                :style="{ width: passwordStrength * 33.3 + '%' }"
              ></div>
            </div>
            <div class="strength-text">
              <span v-if="passwordStrength === 1" class="weak">弱</span>
              <span v-else-if="passwordStrength === 2" class="medium">中</span>
              <span v-else-if="passwordStrength === 3" class="strong">强</span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="formData.confirmPassword" 
            placeholder="请再次输入密码" 
            type="password" 
            show-password 
          />
        </el-form-item>
        
        <el-form-item label="姓名" prop="firstName">
          <div class="name-inputs">
            <el-input v-model="formData.firstName" placeholder="姓氏" class="name-input" />
            <el-input v-model="formData.lastName" placeholder="名字" class="name-input" />
          </div>
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="formData.agreeTerms" prop="agreeTerms">
            我已阅读并同意 <a href="#" class="terms-link">用户协议</a> 和 <a href="#" class="terms-link">隐私政策</a>
          </el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleRegister" 
            :loading="authStore.loading" 
            class="w-full"
          >
            注册
          </el-button>
        </el-form-item>
        
        <el-link type="primary" :underline="false" @click="$router.push('/login')" class="block text-center">
          已有账号？立即登录
        </el-link>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../../stores/auth';

const router = useRouter();
const authStore = useAuthStore();
const formRef = ref();
const passwordStrength = ref(0);

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  firstName: '',
  lastName: '',
  phone: '',
  agreeTerms: false
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value && passwordStrength.value < 2) {
          callback(new Error('密码强度不够，请使用更复杂的密码'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value !== formData.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  firstName: [
    { required: true, message: '请输入姓氏', trigger: 'blur' }
  ],
  lastName: [
    { required: true, message: '请输入名字', trigger: 'blur' }
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur'
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur'
    }
  ],
  agreeTerms: [
    {
      validator: (_rule: any, value: boolean, callback: any) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

// 检查密码强度
const checkPasswordStrength = (password: string) => {
  let strength = 0;
  
  // 长度检查
  if (password.length >= 8) strength++;
  
  // 包含数字
  if (/\d/.test(password)) strength++;
  
  // 包含字母、特殊字符等
  if (/[a-zA-Z]/.test(password) && /[^a-zA-Z0-9]/.test(password)) strength++;
  
  passwordStrength.value = strength;
};

// 处理注册
const handleRegister = async () => {
  try {
    await formRef.value.validate();
    
    // 准备注册数据
    const registerData = {
      username: formData.username,
      email: formData.email,
      password: formData.password,
      firstName: formData.firstName,
      lastName: formData.lastName,
      phone: formData.phone
    };
    
    // 调用注册服务
    await authStore.register(registerData);
    
    ElMessage.success('注册成功，请登录');
    router.push('/login');
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '注册失败，请重试');
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.register-form {
  width: 500px;
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-form h2 {
  text-align: center;
  margin-bottom: 1.5rem;
}

/* 密码强度指示器样式 */
.password-strength {
  margin-top: 8px;
}

.strength-bar {
  height: 4px;
  background-color: #e0e0e0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-indicator {
  height: 100%;
  transition: width 0.3s, background-color 0.3s;
  border-radius: 2px;
}

.strength-indicator.weak {
  background-color: #f56c6c;
}

.strength-indicator.medium {
  background-color: #e6a23c;
}

.strength-indicator.strong {
  background-color: #67c23a;
}

.strength-text {
  font-size: 12px;
  margin-top: 4px;
}

.strength-text .weak {
  color: #f56c6c;
}

.strength-text .medium {
  color: #e6a23c;
}

.strength-text .strong {
  color: #67c23a;
}

/* 姓名输入框样式 */
.name-inputs {
  display: flex;
  gap: 10px;
}

.name-input {
  flex: 1;
}

/* 用户协议链接样式 */
.terms-link {
  color: #409eff;
}

.terms-link:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-form {
    width: 90%;
    margin: 20px;
    padding: 1.5rem;
  }
  
  .name-inputs {
    flex-direction: column;
  }
  
  .name-input {
    width: 100%;
  }
}
</style>